package com.example.juccode.juc01threadpool.demo04;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author: zhongkui 1365693530@qq.com
 * @Date: 2025/10/23
 */
public class Demo04 {
    /**
     * invokeAll 批量提交任务
     */
    public static void main(String[] args) {

        //创建任务列表
        ArrayList<TaskDemo> tasks = new ArrayList<>();
        //填充任务列表
        for (int i = 1; i <= 10; i++) {
            //添加任务
            tasks.add(new TaskDemo(i));
        }
        // 创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        try {
            //提交任务列表
            List<Future<Integer>> futures = threadPool.invokeAll(tasks);
            //遍历执行结果列表
            for (Future<Integer> future : futures) {
                System.out.println("等于=" + future.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

}

class TaskDemo implements Callable<Integer> {
    /**
     * 任务编号
     */
    private final int index;

    public TaskDemo(int index) {
        this.index = index;
    }

    @Override
    public Integer call() throws Exception {
        Thread.sleep(1000);
        return index;
    }
}
